//-----------------------------------------------
//		DAC7614.h
//	DAC7614 Digital2Analog library
//	Arthur Benemann 22/10/2012
//-----------------------------------------------
//	Description:
//      Routines to comunicate with the IC DAC7614 via SPI
//-----------------------------------------------
#include "DAC7614.h"
#include "picDev.h"

unsigned char writeSPI(unsigned int b);

void initDAC7614() {
    DAC_LOAD = 1;
    DAC_LOADtris = 0;
    DAC_SCK = Ro_SCK2OUT;
    DAC_SDI = Ro_SDO2;

    // init the spi module for a slow (safe) clock speed first
    SPI2CON1 = 0x072e; // CKE=1; CKP=1, sample middle,  1:4
    SPI2CON1bits.SPRE=0x4;
    SPI2CON1bits.PPRE=0x3;
    SPI2STAT = 0x8000; // enable the peripheral
}

void writeDAC(unsigned int a) {
    writeSPI((a)&0x0FFF);
    DAC_LOAD = 0;
    Nop();Nop();
    DAC_LOAD = 1;
}

unsigned char writeSPI(unsigned int b) {
    SPI2BUF = b; // write to buffer for TX
    while (!SPI2STATbits.SPIRBF); // wait transfer complete
    return SPI2BUF; // read the received value
}

